package com.demo.buffer;

import java.nio.Buffer;
import java.nio.IntBuffer;

/**
 * 测试nio中buffer的各项操作
 */
public class BufferPositionLimit {

    public static void main(String[] args) {
        /*
        注：注解标识的是程序执行完此行后的结果，而不是断点执行到该行的结果
         */
        IntBuffer buffer = IntBuffer.allocate(10);//position = 0,limit = capacity = 10
        buffer.put(1);//position = 1,limit = capacity = 10
        buffer.put(2);//position = 2,limit = capacity = 10
        buffer.put(3);//position = 3,limit = capacity = 10
        System.out.println( buffer.get());//position = 4,limit = capacity = 10，
        // 这一步我们将读到0，// 一个不是我们放进去的值，  这是由于java在实现数组的时候，默认会根据类型初始化，
        // int类型初始化为0。从这可以看到不调用flip是无法读到刚刚写入的值的
        buffer.flip();//position = 0,limit = 4, capacity = 10
        System.out.println(buffer.get());//position = 1,limit = 4, capacity = 10，读到了0号元素1
        System.out.println(buffer.get());//position = 2,limit = 4, capacity = 10，读到了1号元素2
        System.out.println(buffer.get());//position = 3,limit = 4, capacity = 10，读到了2号元素3

        buffer.clear();//position = 0,limit = capacity = 10,即初始状态

        buffer.put(1);//position = 1,limit = capacity = 10
        buffer.put(2);//position = 2,limit = capacity = 10
        buffer.put(3);//position = 3,limit = capacity = 10
        buffer.rewind();//position = 0,limit = capacity = 10
        //rewind方法只是让position回到了0，此时继续写将意味着覆盖原来的数据，而我们如果希望从头覆盖前2个数据的话，此方法更有用
        buffer.put(4);//position = 1,limit = capacity = 10
        buffer.put(5);//position = 2,limit = capacity = 10
        //此时buffer中保存的是4，5，3

        buffer.position(1);//position = 1,limit = capacity = 10
        buffer.put(6);//position = 2,limit = capacity = 10
        //此时buffer中保存的是4，6，3

        buffer.mark();//mark = position = 2,limit = capacity = 10
        buffer.put(7);//mark = 2, position = 3,limit = capacity = 10
        buffer.put(8);//mark = 2, position = 4,limit = capacity = 10
        buffer.reset();//mark = 2, position = 2,limit = capacity = 10
        //mark应该配合reset使用，这将使position回到当初mark的位置

        System.out.println(buffer.remaining());//输出8
        buffer.flip();//mark = 2, position = 0,limit = 2,capacity = 10
        System.out.println(buffer.remaining());//输出2
        //remaining()返回limit-position的值，即还有多少数据可读，不用该在刚写完的时候调用此方法
        System.out.println("end");
    }
}
